﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using BrainTechLLC;
using System.Windows.Media.Imaging;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using BrainTechLLC.WebCamLib3;

namespace WebCam
{
    /// <summary>
    /// Interaction logic for SelectCaptureDevice.xaml
    /// </summary>
    public partial class SelectCaptureDevice : UserControl
    {
        public event EventHandler<ObjectEventArgs<LocalVideoDevice>> UseDevice;

        public static readonly DependencyProperty CaptureDevicesProperty =
            DependencyProperty.Register("CaptureDevices", typeof(LocalVideoDevicesViewModel), typeof(SelectCaptureDevice), new PropertyMetadata(null, OnCaptureDevicesPropertyChanged));

        public LocalVideoDevicesViewModel CaptureDevices
        {
            get { return (LocalVideoDevicesViewModel)GetValue(CaptureDevicesProperty); }
            set { SetValue(CaptureDevicesProperty, value); }
        }

        private static void OnCaptureDevicesPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            SelectCaptureDevice source = d as SelectCaptureDevice;
            source.UpdateCaptureDevices(e.OldValue as LocalVideoDevicesViewModel, e.NewValue as LocalVideoDevicesViewModel);
        }

        private void UpdateCaptureDevices(LocalVideoDevicesViewModel viewModelOld, LocalVideoDevicesViewModel viewModelNew)
        {
            CaptureDevices = viewModelNew;

            // Let the UI bind to the view-model.
            this.DataContext = CaptureDevices;
        }

        public SelectCaptureDevice()
        {
            InitializeComponent();
        }

        public void OnUseDevice()
        {
            if (UseDevice != null)
            {
                UseDevice(this, new ObjectEventArgs<LocalVideoDevice>(CaptureDevices.Selected));
            }
        }

        private void btnUse_Click(object sender, RoutedEventArgs e)
        {
            OnUseDevice();
        }

        private void cboEntries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CaptureDevices.Selected = cboEntries.SelectedItem as LocalVideoDevice;
        }
    }
}
